package com.lovezy.platform.together.service.impl;

import com.lovezy.platform.core.base.enums.StatusEnum;
import com.lovezy.platform.core.base.query.Pager;
import com.lovezy.platform.core.base.service.MapperService;
import com.lovezy.platform.together.enums.PayStatus;
import com.lovezy.platform.together.exception.TogetherException;
import com.lovezy.platform.together.mapper.TogetherDetailMapper;
import com.lovezy.platform.together.model.TogetherDetail;
import com.lovezy.platform.together.model.TogetherDetailExample;
import com.lovezy.platform.together.service.TogetherDetailService;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

import static com.lovezy.platform.together.exception.TogetherExceptionEnum.HAS_NOT_EXIST_IN_TOGETHER;

/**
 * 约局详情人服务实现
 * Created by jin on 2017/11/20.
 */
@Service
public class TogetherDetailServiceImpl extends MapperService<TogetherDetail,Integer,TogetherDetailMapper>implements TogetherDetailService{

    @Override
    public TogetherDetail addOne(@NotNull Integer togetherId, @NotNull String mid) {
        Date now = new Date();
        TogetherDetail detail = new TogetherDetail();
        detail.setTogetherId(togetherId);
        detail.setCreateId(mid);
        detail.setModifyId(mid);
        detail.setMemberId(mid);
        detail.setPayStatus(PayStatus.PAID.value());
        detail.setGmtCreate(now);
        detail.setGmtModify(now);
        detail.setStatus(StatusEnum.NORMAL.value());
        mapper.insert(detail);
        return detail;
    }

    @Override
    public Optional<TogetherDetail> findById(Integer id) {
        return Pager.doSingleton(() -> mapper.selectByPrimaryKey(id));
    }

    @Override
    public void removeOne(@NotNull Integer detailId, @NotNull String mid) {
        TogetherDetail detail = mapper.selectByPrimaryKey(detailId);
        if (detail == null || !mid.equals(detail.getMemberId())) {
            throw new TogetherException(HAS_NOT_EXIST_IN_TOGETHER);
        }
        TogetherDetail updateDetail = new TogetherDetail();
        updateDetail.setTogetherDetailId(detailId);
        updateDetail.setGmtModify(new Date());
        updateDetail.setModifyId(mid);
        updateDetail.setStatus(StatusEnum.DELETED.value());
        mapper.updateByPrimaryKeySelective(updateDetail);
    }

    @Override
    public boolean hasExistInTogether(String mid, Integer togetherId) {
        TogetherDetailExample example = new TogetherDetailExample();
        example.createCriteria()
                .andMemberIdEqualTo(mid)
                .andTogetherIdEqualTo(togetherId)
                .andStatusEqualTo(StatusEnum.NORMAL.value());
        return mapper.countByExample(example) != 0;
    }

}
